/**
 * @title: MysqlDataSource
 * @projectName mscloud
 * @Description TODO
 * @Author
 * @Date 2022/2/18 14:33
 */
package com.atguigu.springcloud.cloudsentinelgatewaydevelop.sentinel.datasource;

import com.alibaba.csp.sentinel.datasource.AutoRefreshDataSource;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.bean.dto.SentinelAuthorityRuleDTO;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.sentinel.convert.impl.AuthorityRuleMysqlConverter;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.service.AuthorityRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class AuthorityRuleMysqlDataSource extends AutoRefreshDataSource<List<SentinelAuthorityRuleDTO>, List<AuthorityRule>> {
    @Value("${spring.application.name}")
    String applicationName;
    @Autowired
    AuthorityRuleService authorityRuleService;
    public AuthorityRuleMysqlDataSource(AuthorityRuleMysqlConverter authorityRuleMysqlConverter){
        super(authorityRuleMysqlConverter,authorityRuleMysqlConverter.getRecommendRefreshMs());
    }
    @PostConstruct
    public void init(){
        try {
            List<AuthorityRule> newValue = loadConfig();
            getProperty().updateValue(newValue);
        } catch (Throwable e) {
            RecordLog.info("RuleMysqlDataSource loadConfig exception", e);
        }
    }
    @Override
    public List<SentinelAuthorityRuleDTO> readSource() throws Exception {
        Flux<SentinelAuthorityRuleDTO> byApplicationName =
                authorityRuleService.findByApplicationName(applicationName);
        return byApplicationName.collectList().block();
    }

}
